<template>
  <view>
    <button @click="searchBle">搜索蓝牙</button>
    <view
      style="margin-top: 30upx"
      :key="index"
      v-for="(item, index) in devices"
    >
      <button style="width: 400upx; color: #0081ff" @click="onConn(item)">
        {{ item.name }}
      </button>
    </view>
    <button style="margin-top: 100upx" @click="senBleLabel()">标签打印</button>

    <button style="margin-top: 100upx" @click="jumpOld()">BLE蓝牙</button>
    <textarea
      auto-height
      placeholder-style="color:#F76260"
      placeholder="请输入票据信息"
      v-model="piaojuText"
    />
    <button style="margin-top: 100upx" @click="senBleLabel2()">票据打印</button>

    <canvas
      :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
      canvas-id="firstCanvas"
      id="firstCanvas"
      class="firstCanvas"
    />
  </view>
</template>

<script>
import tsc from "@/static/libs/tsc.js";
import esc from "@/static/libs/esc.js";
import bluetoothTool from "@/static/libs/BluetoothTool.js";

export default {
  data() {
    return {
      devices: [],
      currDev: null,
      connId: "",
      piaojuText: "",

      tableDomId: "",
      tableImgPath: "",

      canvasWidth: 800,
      canvasHeight: 600,

      msg: "",
    };
  },
  watch: {
    msg() {
      uni.showToast({
        title: this.msg,
      });
    },
  },
  onReady() {
    this.renderCanvas();
  },
  mounted() {
    //#ifdef APP-PLUS
    // 蓝牙
    bluetoothTool.init({
      listenBTStatusCallback: (state) => {
        if (state == "STATE_ON") {
          let lastBleAddress = uni.getStorageSync("lastBleAddress");
          if (lastBleAddress) {
            uni.showLoading({
              title: "正在连接...",
            });
            console.log(lastBleAddress);
            bluetoothTool.connDevice(lastBleAddress, (result) => {
              uni.hideLoading();
              uni.showToast({
                title: result ? "连接成功！" : "连接失败...",
              });
            });
          }
        }
      },
      discoveryDeviceCallback: this.onDevice,
      discoveryFinishedCallback: function () {
        that.msg = "搜索完成";
      },
      readDataCallback: function (dataByteArr) {
        // 读取蓝牙返回的数据
        /* if(that.receiveDataArr.length >= 200) {
							that.receiveDataArr = [];
						}
						that.receiveDataArr.push.apply(that.receiveDataArr, dataByteArr); */
      },
      connExceptionCallback: function (e) {
        console.log(e);
        that.msg = "设备连接失败";
      },
    });
    //#endif
  },
  methods: {
    destroyed: function () {
      console.log("destroyed----------");
      if (this.connId != "") {
        uni.closeBLEConnection({
          deviceId: this.connId,
          success(res) {
            console.log(res);
          },
        });
      }
    },
    searchBle() {
      var that = this;
      console.log("initBule");
      // 使用openBluetoothAdapter 接口，免去主动申请权限的麻烦
      uni.openBluetoothAdapter({
        success(res) {
          this.devices = [];
          console.log("打开 蓝牙模块，开始搜索模式...");
          console.log(res);
          bluetoothTool.discoveryNewDevice();
          //that.onDevice()
        },
      });
    },
    onDevice(newDevice) {
      console.log("监听寻找到新设备的事件---------------");
      console.log(newDevice);
      if (newDevice.name && newDevice.name != "null") {
        this.devices.push({
          name: newDevice.name,
          address: newDevice.address,
        });
      }
    },
    stopFindBule() {
      console.log("停止搜寻附近的蓝牙外围设备---------------");
      uni.stopBluetoothDevicesDiscovery({
        success(res) {
          console.log(res);
        },
      });
    },
    onConn(item) {
      console.log("连接蓝牙---------------" + item.address);

      bluetoothTool.connDevice(item.address, (result) => {
        if (result) {
          uni.setStorageSync("lastBleAddress", item.address);
        }
        console.log("连接结果：", result);
      });
    },
    senBleLabel() {
      //标签模式
      var command = tsc.jpPrinter.createNew();
      command.init();
      command.setCls(); //清除缓冲区，防止下一个没生效
      command.setSize(50, 70); //设置标签大小，单位mm.具体参数请用尺子量一下
      command.setCls(); //清除缓冲区
      command.setBox(8, 10, 550, 750, 5); //绘制一个边框
      command.setBar(10, 70, 550, 5); //绘制第一条横线
      command.setBar(10, 140, 550, 5); //绘制第二条横线
      command.setBar(10, 210, 550, 5); //绘制第三条横线
      command.setBar(10, 280, 550, 5); //绘制第四条横线
      command.setBar(10, 420, 550, 5); //绘制第五条大横线
      command.setBar(10, 480, 550, 5); //绘制第六条大横线
      command.setBar(10, 540, 550, 5); //绘制第七条大横线

      command.setText(16, 30, "TSS24.BF2", 2, 1, "样品名称");
      command.setText(16, 90, "TSS24.BF2", 2, 1, "样品类型");
      command.setText(16, 160, "TSS24.BF2", 2, 1, "采样时间");
      command.setText(16, 230, "TSS24.BF2", 2, 1, "采样类型");
      command.setText(16, 330, "TSS24.BF2", 2, 1, "经纬度");
      command.setText(16, 450, "TSS24.BF2", 2, 1, "土壤类型");
      command.setText(16, 510, "TSS24.BF2", 2, 1, "采样深度");
      command.setText(16, 570, "TSS24.BF2", 2, 1, "样品交接记录表号");

      command.setBar(200, 10, 5, 750); //绘制一条黑线
      // command.setBar(16, 100, 5, 750); //绘制一条黑线

      command.setPagePrint();
      let data = command.getData();
      bluetoothTool.sendByteData(data);
      console.log("发送完毕");
    },
    senBleLabel2() {
      //票据模式
      var command = esc.jpPrinter.createNew();
      command.init();
      command.setText(this.piaojuText);
      command.setPrintAndFeedRow(1);
      bluetoothTool.sendData(command.getRawData());
    },
    renderCanvas() {
      let filePath = "../../static/xtHead.jpg";
      let that = this;
      const firstCanvas = uni.createCanvasContext("firstCanvas", this);
      let scla = 1;
      uni.getImageInfo({
        src: filePath,
        success(res) {
          console.log(res.width + "--" + res.height);
          that.canvasWidth = res.width * scla;
          that.canvasHeight = res.height * scla;
          console.log(res, that.canvasWidth, that.canvasHeight);
          firstCanvas.drawImage(
            filePath,
            0,
            0,
            that.canvasWidth,
            that.canvasHeight
          );
          firstCanvas.draw();
          that.$nextTick(() => {
            //获取画布像素数据
          });
        },
        fail(res) {
          console.log(res);
        },
      });
    },
    jumpOld() {
      uni.navigateTo({
        url: "./miniAppPrint",
      });
    },
  },
};
</script>

<style></style>
